/**
 * JAXBUtilities.java
 * Nov 14, 2013
 * Copyright: phongtdse60732@fpt.edu.vn
 */
package XMLUtilities;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

/**
 * @author trandophong
 * @version 1.0
 */
public class JAXBUtilities {
	public static void marshall_toOutputStream(Object obj, OutputStream os) {
		JAXBContext jc;
		try {
			jc = JAXBContext.newInstance(obj.getClass());
			Marshaller ms = jc.createMarshaller();
			ms.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			ms.marshal(obj, os);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
	}

	public static void marshall_toFile(String filePath, Object obj) {
		JAXBContext jc;
		try {
			jc = JAXBContext.newInstance(obj.getClass());
			Marshaller ms = jc.createMarshaller();
			ms.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
			ms.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

			File f = new File(filePath);
			if (!f.exists()) {
				f.createNewFile();
			}
			ms.marshal(obj, f);
		} catch (JAXBException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Object unmarshall(String filePath, Object obj) {
		Object result = null;
		try {
			JAXBContext jc = JAXBContext.newInstance(obj.getClass());
			Unmarshaller u = jc.createUnmarshaller();
			File f = new File(filePath);
			// JAXBElement jax = (JAXBElement) u.unmarshal(f);
			// Customer item = (Customer) jax.getValue();
			result = u.unmarshal(f);
		} catch (JAXBException e) {
			e.printStackTrace();
		}
		return result;
	}
}
